<template>
  <div>
    <!-- 面包屑导航区域 -->
    <Break></Break>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        :closable="false"
        show-icon
      >
      </el-alert>
      <div class="selectType">
        <span>选择商品分类：</span>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="selectValue"
          :options="selectOptions"
          :props="cateProps"
          @change="selectChange"
        ></el-cascader>
      </div>
      <el-tabs
        type="card"
        class="tabsCard"
        v-model="activeName"
        @tab-click="tabClick"
      >
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数 -->
          <el-button
            type="primary"
            size="mini"
            class="btn"
            :disabled="btnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 添加参数 表格 -->
          <el-table :data="manyParams" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="attrHandleClose(tag)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" prop="id">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性 -->
          <el-button
            type="primary"
            size="mini"
            class="btn"
            :disabled="btnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 添加属性表格 -->
          <el-table :data="onlyParams" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="attrHandleClose(tag)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" prop="id">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 修改动态参数弹出框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editManyDialogVisible"
      width="30%"
    >
      <el-form
        :model="editManyRuleForm"
        :rules="editManyRules"
        ref="edifManyRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="editManyRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editManyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editMany">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="30%"
    >
      <el-form
        :model="addParamsForm"
        :rules="editManyRules"
        ref="addRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import goodAPI from "../../http/API/Good"
import Break from "../bread";
export default {
  data() {
    return {
      selectValue: [],
      selectOptions: [],
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyParams: [],
      onlyParams: [],
      activeName: "many",
      editManyDialogVisible: false,
      addDialogVisible: false,
      editManyRuleForm: {
        attr_name: "",
        cat_id: null,
        attr_sel: "",
        attr_vals: null,
      },
      editManyRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      addParamsForm: {
        attr_name: "",
      },
    };
  },
  components: {
    Break,
  },
  methods: {
    //  展示级联选择器的数据
    getCategoriesData() {
      this.$http.get("categories").then((res) => {
        // console.log(res);
        this.selectOptions = res.data.data;
      });
    },
    // 级联选择器回调函数
    selectChange() {
      //   console.log(this.selectValue);
      this.getCategoriesAttrData();
    },
    // 选项卡回调函数
    tabClick() {
      this.getCategoriesAttrData();
    },
    async getCategoriesAttrData() {
      if (this.selectValue.length !== 3) {
        this.manyParams = [];
        this.onlyParams = [];
        this.selectValue = [];
        return this.$message.error("只允许为三级分类设置参数！");
      }
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((item, index) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      //   console.log(res);
      if (this.activeName === "many") {
        this.manyParams = res.data;
      } else {
        this.onlyParams = res.data;
      }
    },
    showInput() {},
    //删除商品
    delParams(id) {
      this.$http
        .delete(`categories/${this.cateId}/attributes/${id}`)
        .then((res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
          this.getCategoriesAttrData();
        });
    },
    // 反显修改参数
    editParamsDialog(row) {
      console.log(row);
      this.editManyRuleForm.attr_name = row.attr_name;
      this.editManyRuleForm.attr_id = row.attr_id;
      this.editManyRuleForm.attr_sel = row.attr_sel;
      // console.log(this.editManyRuleForm.attr_sel);
      this.editManyDialogVisible = true;
    },
    //确定修改参数
    editMany() {
      this.$refs.edifManyRuleFormRef.validate(async (valid) => {
        if (valid) {
          let { data: res } = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editManyRuleForm.attr_id}`,
            this.editManyRuleForm
          );
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.getCategoriesAttrData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.editManyDialogVisible = false;
    },
    // 添加
    addParams() {
      this.$refs.addRuleFormRef.validate(async (valid) => {
        if (valid) {
          this.$http
            .post(`categories/${this.cateId}/attributes`, {
              attr_name: this.addParamsForm.attr_name,
              attr_sel: this.activeName,
            })
            .then((res) => {
              console.log(res);
              if (res.data.meta.status !== 201) {
                return this.$message.error("添加参数失败");
              }
              this.$message.success("添加参数成功");
              this.getCategoriesAttrData();
              (this.addParamsForm.attr_name = ""),
                (this.addDialogVisible = false);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    attrHandleClose(data){
      console.log(data)
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    showInput(info) {
      info.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async saveAttrVals(row) {
      const { data:res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数献给失败");
      }
      this.$message.success("修改数据项成功");
    },
    tagHandClose(Index, row) {
      row.attr_vals.splice(Index, 1);
      this.saveAttrVals(row);
    },
  },
  created() {
    this.getCategoriesData();
    // this.getCategoriesAttrData();
  },
  computed: {
    cateId() {
      return this.selectValue[this.selectValue.length - 1];
    },
    btnDisabled() {
      return this.selectValue.length !== 3;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style scoped>
.box-card {
  margin-top: 20px;
}
.selectType {
  margin-top: 20px;
}
.tabsCard {
  margin-top: 20px;
}
.btn {
  margin-bottom: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>